//
//  DYYuYueViewController.swift
//  SheYangBigData
//
//  Created by 宋海胜 on 2021/1/5.
//  Copyright © 2021 叁拾叁. All rights reserved.
//


import UIKit
import SwiftDate

class DYYuYueViewController: SYBaseViewController, UITableViewDelegate, UITableViewDataSource {
    
    var jingquModel: DYJingquDetailModel!
    var ticketName: String!
    var peoples:[DYJQYuyuePeopleListModel] = []
    var times:[DYJQYuyueTimeModel] = []
    var tableView: UITableView!
    var alert: DYYuyueAlert!
    var bottom: DYYuyueBottomView!
    let mingxi = DYOrderDetailView()
    let riliVC = DYRiliViewController()
    var id: String!
    var dingdanParams: [String: Any] = [:]
    var danjia: Double = 0.0 {
        didSet {
            self.zongjia()
        }
    }
    var zhangshu: Int = 1 {
        didSet {
            self.zongjia()
        }
    }
    var renshu: Int = 0 {
        didSet {
            self.zongjia()
        }
    }
    var selectTime: String = "" {
        didSet {
            self.zongjia()
        }
    }
    
    init(id: String, jingquModel: DYJingquDetailModel, ticketName: String) {
        super.init(nibName: nil, bundle: nil)
        self.ticketName = ticketName
        self.jingquModel = jingquModel
        self.id = id
        self.dingdanParams["number"] = "1"
        self.dingdanParams["ticketId"] = id
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setTableView()
        
        self.title = "门票预约"
        setSearchView()
        let now = Date()
        let nowStr = now.sy_toString(format: "yyyy-MM-dd")
        getData(time: nowStr)
        getPeopleList()
    }
    
    func getData(time: String) {
                
        requestVM.baseRequest(disposeBag: dispose, type: .dy_jingquYuyue(dic:["ticketId":self.id, "reservationDate":"\(time)"]), modelClass: SGBaseNoPageListModel<DYJQYuyueTimeModel>.self) {[weak self] (res) in
            if let `self` = self {
                DispatchQueue.main.async {
                    
                    self.times = res.data ?? []
                    self.tableView.reloadData()
                }
            }
            
        } Error: {
            
        }
    }
    
    func getPeopleList() {
                
        requestVM.baseRequest(disposeBag: dispose, type: .dy_jingquPeopleList, modelClass: SGBaseNoPageListModel<DYJQYuyuePeopleListModel>.self) {[weak self] (res) in
            if let `self` = self {
                self.peoples = res.data ?? []
                self.tableView.reloadData()
            }
            
        } Error: {
            
        }
    }
    
    func deletePeople(id: String) {
        
        requestVM.baseRequest(disposeBag: dispose, type: .dy_jingquPeopleDelete(id: id), modelClass: SGBaseModel<SGPagerTestModel>.self) {[weak self] (res) in
            if let `self` = self {
                self.refreshPeoples()
            }
            
        } Error: {
            
        }
    }
    
    /// <#Description#>
    func addDingdan() {
        
        if let v = self.dingdanParams["reservationDate"] {
            if (v as! String).isEmpty {
                self.sy_toast("请选择日期")
                return
            }
        } else {
            self.sy_toast("请选择日期")
            return
            
        }
        if let v = self.dingdanParams["orderDetails"] {
            if (v as! String).isEmpty {
                self.sy_toast("请选择人员")
                return
            }
        } else {
            self.sy_toast("请选择人员")
            return
            
        }
//        let vc = DYJingquDaifukuanVC(id:1)
//        self.sy_push(vc)
//        return
        requestVM.baseRequest(disposeBag: dispose, type: .dy_jingquYuyueAdd(dic: self.dingdanParams), modelClass: SGBaseModel<SGPagerTestModel>.self) {[weak self] (res) in
            if let `self` = self {
                let vc = DYJingquDaifukuanVC(id:1)
                self.sy_push(vc)
            }

        } Error: {

        }
    }
    
    func refreshPeoples() {
        self.getPeopleList()
    }
    
    func setSearchView() {
        self.setMingxi()
        bottom = DYYuyueBottomView(frame: CGRect(x: 0, y: SCREEN_HEIGHT - 56.autoWidth() - BOTTOM_SAFE_HEIGHT, width: SCREEN_WIDTH, height: 56.autoWidth()))
        bottom.currentVC = self
        self.view.addSubview(bottom)
        
    }
    
    func setMingxi() {
        
        self.view.addSubview(mingxi)
        mingxi.snp.makeConstraints { (make) in
            make.bottom.equalToSuperview().offset(-56.autoWidth()-BOTTOM_SAFE_HEIGHT)
            make.top.left.right.equalToSuperview()
        }
    }
    
    func setAlert() {
        alert = DYYuyueAlert()
        let window = UIApplication.shared.keyWindow
        window?.addSubview(alert)
        alert.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
    }
    
    func zongjia() {
        self.mingxi.configureMenpiao(jingquModel.name ?? "", self.selectTime, "\(self.ticketName ?? "")", "\(self.danjia)",  zhangshu*renshu)
        self.bottom.configure("\(danjia*Double(zhangshu)*Double(renshu))", "0.0")
    }

    func setTableView() {
        
        //创建表格视图
        self.tableView = UITableView(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: SCREEN_HEIGHT-BOTTOM_SAFE_HEIGHT - 56.autoWidth()), style:.plain)
        self.tableView.separatorStyle = .none
        self.tableView.backgroundColor = Constant.bgViewColor
        self.tableView.delegate = self
        self.tableView.dataSource = self
        self.tableView!.register(DYYuyueTimeCell.self, forCellReuseIdentifier: "DYYuyueTimeCell")
        self.tableView!.register(DYYuyueNumCell.self, forCellReuseIdentifier: "DYYuyueNumCell")
        self.tableView!.register(DYYuyueMenpiaoCell.self, forCellReuseIdentifier: "DYYuyueMenpiaoCell")
        
        
        self.view.addSubview(self.tableView!)
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 3
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.row == 0 {
            let cell: DYYuyueTimeCell? = tableView.dequeueReusableCell(withIdentifier: "DYYuyueTimeCell") as? DYYuyueTimeCell
            cell?.selectionStyle = .none
            cell?.moreBt.addAction {[weak self] in
                if let `self` = self {
                    
                    let view = UIView()
                    view.tag = 7
                    self.riliVC.setupRili(view)
                    self.riliVC.sureBlock = {[weak self] (selectTime, selectModel) in
                        if let `self` = self {
                            self.danjia = Double(self.times[indexPath.row].money ?? "0.0") ?? 0.0
                            let times = self.times[0].t?.components(separatedBy: " ")
                            self.dingdanParams["reservationDate"] = times?.first
                            self.selectTime = times?.first ?? ""
                            
                            cell?.lastIndexPath = IndexPath(item: 0, section: 0)
                            self.getData(time: selectTime)
                        }
                        }
                }
            }
            cell?.clickedClosure = {[weak self] index in
                if let `self` = self {
                    self.danjia = Double(self.times[indexPath.row].money ?? "0.0") ?? 0.0
                    let times = self.times[index].t?.components(separatedBy: " ")
                    self.selectTime = times?.first ?? ""
                    self.dingdanParams["reservationDate"] = times?.first
                }
            }
            cell?.configureView(self.times)
            return cell!
        } else if indexPath.row == 1 {
            let cell: DYYuyueNumCell? = tableView.dequeueReusableCell(withIdentifier: "DYYuyueNumCell") as? DYYuyueNumCell
            cell?.selectionStyle = .none
            cell?.clickedClosure = {[weak self] index in
                if let `self` = self {
                    self.dingdanParams["number"] = "\(index)"
                    self.zhangshu = index
                }
            }
            
            return cell!
        } else {
            let cell: DYYuyueMenpiaoCell? = tableView.dequeueReusableCell(withIdentifier: "DYYuyueMenpiaoCell") as? DYYuyueMenpiaoCell
            cell?.selectionStyle = .none
            cell?.currentVC = self
            cell?.configureView(self.peoples)
            cell?.passParamsClosure = {[weak self] ids in
                if let `self` = self {
                    var dics:[[String: String]] = []
                    (ids as! [String]).forEach { (id) in
                        let dic:[String: String] = ["peopleId": id]
                        dics.append(dic)
                    }
                    
                    self.dingdanParams["orderDetails"] = dics.getJSONString()
                    self.renshu = dics.count
                }
            }
            return cell!
        }
        
    }
    
    func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
        print("liangTableView手势冲突了")
    }
    
    @objc func tijiaoAction() {
        setAlert()
    }
}
